package com.mercury.beans;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateUtil {
	private static final SessionFactory factory;
	static {
		try{
			 factory = new Configuration().configure().buildSessionFactory();
			}catch (HibernateException e){
				throw new RuntimeException(e.getMessage(),e);
			}
}
	private static final ThreadLocal<Session> session = new ThreadLocal<Session>();

	public static SessionFactory getSessionFactory(){
		return factory;
	}

	public static Session currentSession() throws HibernateException{
		Session s = session.get();
		if(s==null){
			s = factory.openSession();
			session.set(s);
		}
		return s;
	}
	public static void closeSession() throws HibernateException{
		Session s = session.get();
		session.set(null);
		if(s!=null) s.close();
	}
}
